import axios from 'axios'
import qs from 'qs'
import { getLocalStorage } from '@/assets/js/common'

const instance = axios.create({
    baseURL: process.env.API_URL,
    timeout: 10000,
})

// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// http request拦截器 在所以请求发送之前，检测是否存在 token，如果存在则放到请求头中
instance.interceptors.request.use(function(config) {
    let token = getLocalStorage('token', 'string')
    if (token) {
        config.headers.token = token;
    }
    return config;
}, function(error) {
    return Promise.reject(error);
});

export default function ajax(url, data = {}, type = 'get') {
    return new Promise((resolve, reject) => {
        let promise = null
        type = type.toUpperCase()
            //请求类型为GET
        if (type === 'GET') {
            promise = instance.get(url, { params: data })
        }
        //请求类型为POST
        if (type === 'POST') {
            promise = instance.post(url, qs.stringify(data))
        }
        promise.then((res) => {
            resolve(res.data)
        }).catch((err) => {
            reject(err)
        })

    })
}